'''检索并浏览网络图片记录的应用.

界面复杂但应用内容简单,只有一个postMethod:search
参数{}为:
type:分类
tags:标签字符串,以,隔开
days:日数
返回{result:{图片地址:图片名字}}

另外getPage也要渲染一下,需要重载.
'''

import sys
import os
import time

from flask import render_template

from BaseApp import BaseApp

## 导入classes文件夹
sys.path.append(os.path.join(sys.path[0], r'classes'))
from _MyDatabase import MyDatabase

class WebPicView(BaseApp):

  def __init__(self):
    BaseApp.__init__(self, 'WebPicView')
    self._db = MyDatabase(os.path.join(
      sys.path[0],
      'database', 'WebPicDatabase.json')
    )
    return
  
  ## 由于不是只有一个页面,重写一个默认页面  
  def getPage(self, page, flaskRequest):
    if (page == 'WebPicView.html'):
      self._db = MyDatabase(os.path.join(
        sys.path[0],
        'database', 'WebPicDatabase.json')
      )
      types = ['ALL']+[key for key in self._db._json]
      tags = ['ALL']+[tag for tag in self._db.getTags()]
      days = [['5天内', '5'], ['10天内', '10'], ['30天内', '30'], 
        ['120天内', '120'], ['不限', 'ALL']]
      print(types, tags, days)
      return render_template(f'{self._appname}/{page}', types = types,
        tags = tags, days = days)
    return None
    
  def postMethod(self, methodName, flaskRequest):
    print('WebPicView.postMethod - {methodName}')
    if (methodName == 'search'):
      _type = flaskRequest.form['type']
      if _type == 'ALL':
        _type = None
      tags = flaskRequest.form['tags'].strip().split(',')
      if 'ALL' in tags:
        tags = None
      startTime = 0
      if flaskRequest.form['days'] != 'ALL':
        startTime = int(time.time()) - int(flaskRequest.form['days'])*86400
      searchResult = self._db.search(_type, tags, startTime, -1)
      result = {'result':{}}
      for x in searchResult:
        result['result'][x['content']] = x['name']
      return result
    return